package com.ml.mall.api.company;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.ml.mall.annotation.LogMethodInvokeInformation;
import com.ml.mall.annotations.OperLog;
import com.ml.mall.bean.base.ApiRestResult;
import com.ml.mall.bean.page.Page;
import com.ml.mall.bean.req.company.*;
import com.ml.mall.bean.req.sys.SysUserQueryDto;
import com.ml.mall.bean.res.company.CompanyInfoLevelRes;
import com.ml.mall.bean.res.company.CompanyQueryInfoRes;
import com.ml.mall.bean.res.company.CompanyQueryRes;
import com.ml.mall.consts.CommonConsts;
import com.ml.mall.consts.MailContentConsts;
import com.ml.mall.entity.company.SysCompanyRemark;
import com.ml.mall.enums.CommonEnum;
import com.ml.mall.enums.RetStatusNum;
import com.ml.mall.exception.BizException;
import com.ml.mall.service.company.SysCompanyRemarkService;
import com.ml.mall.service.company.SysCompanyService;
import com.ml.mall.service.company.SysUserCompanyRelationService;
import com.ml.mall.service.sys.SysUserService;
import com.ml.mall.utils.HttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.List;

/**
 *   @description    :公司相关接口
 *   @author         :zxm
 *   @date           :2021/5/13
 *   @version        :1.0
**/
@Api(tags = "【auth】公司信息相关接口")
@RestController
@RequestMapping("/company")
@Slf4j
public class SysCompanyController {

    @Autowired
    private SysCompanyService sysCompanyService;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserCompanyRelationService sysUserCompanyRelationService;
    @Autowired
    private SysCompanyRemarkService sysCompanyRemarkService;

    @Value("${dns.front_url}")
    private String url;

    @ApiOperation(value = "公司信息的创建")
    @PostMapping("/new")
//  @RequiresPermissions(PermissionConst.COMPANY_NEW)
    public ApiRestResult companyNew(@RequestBody @Valid CompanyNewDto dto){
        return sysCompanyService.createCompany(dto);
    }

    @ApiOperation(value = "公司信息的修改")
    @PostMapping("/edit")
//  @RequiresPermissions(PermissionConst.COMPANY_EDIT)
    public ApiRestResult companyEdit(@RequestBody @Valid CompanyEditDto dto){
        return sysCompanyService.editCompany(dto);
    }

    @ApiOperation(value = "公司信息的删除")
    @PostMapping(path = "/del")
//  @RequiresPermissions(PermissionConst.COMPANY_DEL)//未发现调用
    public ApiRestResult companyDel(@RequestBody List<Long> ids){
        if(ids == null || ids.size() < 1){
            return ApiRestResult.err(RetStatusNum.PARAMS_ERROR.getMessage(), RetStatusNum.PARAMS_ERROR.getCode());
        }
        return ApiRestResult.ok(sysCompanyService.deleteByBatchCompanyIds(ids));
    }

    @ApiOperation(value = "公司信息的查询")
    @PostMapping("/query_one")
//  @RequiresPermissions(PermissionConst.COMPANY_QUERY_ONE)
    public ApiRestResult companyQueryOne(@RequestBody CompanyDto dto){
        CompanyQueryInfoRes companyQueryInfoRes = sysCompanyService.queryOneCompany(dto);
        return ApiRestResult.ok(companyQueryInfoRes);
    }


    @ApiOperation(value = "卖家公司所处阶段")
    @PostMapping("/supplier/of_step")
//  @RequiresPermissions(PermissionConst.COMPANY_SUPPLIER_OF_STEP) //未发现调用
    public ApiRestResult companySupplierOfStep(){
        return ApiRestResult.ok(sysCompanyService.getCompanySupplierOfStep());
    }


    @ApiOperation(value = "公司信息的分页查询")
    @PostMapping("/query_page")
//  @RequiresPermissions(PermissionConst.COMPANY_QUERY_PAGE)
    public ApiRestResult companyQueryPage(@RequestBody CompanyQueryDto dto){
        Page<CompanyQueryRes> result = sysCompanyService.queryPageCompany(dto);
        return ApiRestResult.ok(result);
    }

    @ApiOperation(value = "公司信息的注册")
    @PostMapping("/register")
////  @RequiresPermissions(PermissionConst.COMPANY_REGISTER)//放行，不起用
    public ApiRestResult companyRegister(@RequestBody @Valid CompanyRegisterDto dto){
        ApiRestResult backDate =  sysCompanyService.registerCompany(dto);
        log.info("success");
        return backDate;
    }

    @ApiOperation(value = "发送验证码给邮箱")
    @PostMapping("/sendVerificCode")
//  @RequiresPermissions(PermissionConst.COMPANY_SEND_VERIFIC_CODE)//未发现调用
    public ApiRestResult companyRegisterSendVerificCode(@RequestBody @Valid CompanySendVerificCode dto){
        sysCompanyService.companyRegisterSendVerificCode(dto);
        return ApiRestResult.ok();
    }



    @RequestMapping("/getImage")
    //生成验证码之后；ip与code存储到缓存
//    <img src="/getCode" id="codeImg" onclick="refresh()" alt="">
////  @RequiresPermissions(PermissionConst.COMPANY_GET_IMAGE) //放行，不启用
    public void ImgCode(HttpServletResponse response){
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
        try {
            log.info("lineCaptcha.getCode()===={}",lineCaptcha.getCode());
            log.info("requestIp===={}", HttpUtil.getIp());
//           存储到redis
            sysCompanyService.saveCodeToRedis(lineCaptcha.getCode(),HttpUtil.getIp());
            lineCaptcha.write(response.getOutputStream());
        }catch (Exception e){
            e.printStackTrace();
        }
    }





    @PostMapping(value = "/getverfy")
////  @RequiresPermissions(PermissionConst.COMPANY_GET_VERIFY) //放行，不启用
    public void verfy(String code,HttpServletRequest request){
        Boolean isSame = sysCompanyService.verifyCaptchaCode(code,HttpUtil.getIp());
        log.info("isSame===={}",isSame);
        return ;
    }

    @ApiOperation(value = "公司分页查询用户")
    @PostMapping("/user/query")
//  @RequiresPermissions(PermissionConst.COMPANY_QUERY_USER)
    public ApiRestResult companyQueryUser(@RequestBody @Valid SysUserQueryDto dto){
        return ApiRestResult.ok(sysUserService.selectAccByPage(dto));
    }



    @ApiOperation(value = "公司添加用户")
    @PostMapping("/user/add")
//  @RequiresPermissions(PermissionConst.COMPANY_USER_ADD)
    public ApiRestResult companyAddUser(@RequestBody @Valid CompanyRelationAddDto dto){
        int i = sysUserCompanyRelationService.addUserCompany(dto);
        if (i==0){
            throw new BizException(CommonEnum.INSERT_ERROR);
        }
        return ApiRestResult.ok();
    }


    @ApiOperation(value = "公司编辑用户")
    @PostMapping("/user/edit")
    @OperLog(operModul = "company/user", operType = "edit", operDesc = "用户编辑")
    @LogMethodInvokeInformation("公司用户编辑")
//  @RequiresPermissions(PermissionConst.COMPANY_USER_EDIT)//未发现调用
    public ApiRestResult companyEditUser(@RequestBody @Valid CompanyRelationEditDto dto){
        sysUserCompanyRelationService.editUserCompany(dto);
        return ApiRestResult.ok();
    }


    @ApiOperation(value = "公司删除用户")
    @PostMapping("/user/del")
//  @RequiresPermissions(PermissionConst.COMPANY_USER_DEL)
    public ApiRestResult companyDtlUser(@RequestBody @Valid CompanyRelationDelDto dto){
        sysUserCompanyRelationService.delUserCompany(dto);
        return ApiRestResult.ok();
    }


    /**
     * 公司创建用户时，会直接创建账号，该接口已不再使用
     * @param dto
     * @return
     */
    @ApiOperation(value = "用户接受邀请创建账户")
    @PostMapping("/invite/creat_user")
//  @RequiresPermissions(PermissionConst.COMPANY_INVITE_CREATE_USER)//未发现调用
    public ApiRestResult acceptInviteToCreateUser(@RequestBody @Valid CompanyInviteCreateUserDto dto){
        int i = sysUserService.createUserByInvite(dto);
        if (i==0){
            throw new BizException(CommonEnum.INSERT_ERROR);
        }
        return ApiRestResult.ok();
    }

    @ApiOperation(value = "查询当前账号公司信息的完整程度")
    @PostMapping("/info_level/query")
//  @RequiresPermissions(PermissionConst.COMPANY_INFO_LEVEL_QUERY)//未发现调用
    public ApiRestResult queryInfoLevel(){
        CompanyInfoLevelRes companyInfoLevelRes = sysCompanyService.queryInfoLevel();
        if(null == companyInfoLevelRes){
            throw new BizException(CommonEnum.SELECT_ERROR);
        }
        return ApiRestResult.ok(companyInfoLevelRes);
    }

    @ApiModelProperty(value = "添加公司备注信息")
    @PostMapping("/remark/add")
//  @RequiresPermissions(PermissionConst.COMPANY_REMARK_ADD)
    public ApiRestResult addRemark(@RequestBody @Valid CompanyRemarkAddDto dto){
        Integer result = sysCompanyRemarkService.addCompanyRemark(dto);
        if(CommonConsts.FIXED_NUM_ZERO.equals(result)){
            throw new BizException(CommonEnum.INSERT_ERROR);
        }
        return ApiRestResult.ok(result);
    }

    @ApiModelProperty(value = "查询全部的公司备注信息")
    @PostMapping("/remark/query_all")
    public ApiRestResult queryRemark(@RequestBody @Valid CompanyRemarkQueryAllDto dto){
        List<SysCompanyRemark> result = sysCompanyRemarkService.queryAll(dto);
        if(null == result){
            throw new BizException(CommonEnum.SELECT_ERROR);
        }
        return ApiRestResult.ok(result);
    }

    @ApiModelProperty(value = "邮箱验证")
    @GetMapping("/email/verify")
//    @RequiresPermissions(PermissionConst.COMPANY_EMAIL_VERIFY)//放行不启用
    public void verify(@RequestParam("email_address") String emailAddress,HttpServletResponse response) throws IOException {
        boolean verify = sysCompanyService.verify(emailAddress);
        String redirectUrl=url+MailContentConsts.EMAIL_VERIFICATION_PAGE;
        redirectUrl=redirectUrl.replaceAll("EMAIL",emailAddress);
        if(verify){
            redirectUrl=redirectUrl.replaceAll("STATE","1");
        }else {
            redirectUrl=redirectUrl.replaceAll("STATE","0");
        }
        response.sendRedirect(redirectUrl);
    }
}
